package at.jku.se.pr.quickshopper.network;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

import android.util.Log;

/**
 * class which creates a connection to the server
 */
public class ServerConnection extends Thread {
	
	/**
	 * path where the server is located
	 */
	private final String url = "http://192.168.1.107:8090/QuickShopperServer/QuickShopperServer";
	
	/**
	 * string which includes the data to build the connection
	 */
	private String str;
	
	/**
	 * string for the InputStream
	 */
	private String result;
	
	/**
	 * constructor to create a new ServerConnection
	 * 
	 * @param str
	 */
	public ServerConnection(String str) {
		this.str = str;
	}
	
	@Override
	public void run() {
		connectToServer();
	}
	
	/**
	 * method to start the connection to the server
	 */
	protected void connectToServer() {
		result = "error";
    	
        try {
        	DefaultHttpClient httpclient = new DefaultHttpClient();
        	HttpPost httppostreq = new HttpPost(url);
        	
        	StringEntity se = new StringEntity(str);
        	se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        	se.setContentType("application/json;charset=UTF-8");
        	se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
        	httppostreq.setEntity(se);
        	
        	httppostreq.setHeader("Accept", "application/json");
	    	httppostreq.setHeader("Content-type", "application/json");
	    	httppostreq.setHeader("User-Agent", "android");
	    	
	    	HttpResponse httpresponse = httpclient.execute(httppostreq);
        	
        	HttpEntity resultentity = httpresponse.getEntity();
        	InputStream inputstream = resultentity.getContent();
        	result = convertStreamToString(inputstream);
        	inputstream.close();
        } catch (Exception e) {
        	Log.e("connectToServer - ServerConnection", e.toString());
		}
        
	}
	
    /**
     * Converts the InputStream of the HTTP-Request to a string
     * @param is
     * @return string of is
     */
    private String convertStreamToString(InputStream is) {
        String line = "";
        StringBuilder total = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        try {
            while ((line = rd.readLine()) != null) {
                total.append(line);
            }
        } catch (Exception e) {
        	Log.e("convertStreamToString - ServerConnection", e.getMessage());
        }
        return total.toString();
    }
    
	/**
	 * @return the result
	 */
	public String getResult() {
		return result;
	}
    
}
